<template>
  <div>
    <!-- 1.页面展示区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 1.1 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true">
          <el-form-item label="文章分类">
            <el-select
              placeholder="请选择分类"
              size="small"
              v-model="query.cate_id"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select
              placeholder="请选择状态"
              size="small"
              v-model="query.state"
            >
              <el-option value="已发布"></el-option>
              <el-option value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtList"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="doReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="addDialogVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 1.2 文章表格区域 -->
      <el-table :data="artList" border style="width: 100%">
        <el-table-column label="文章标题">
          <template v-slot="scope">
            <el-link type="primary" @click="showInfo(scope.row.id)">{{
              scope.row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类"></el-table-column>
        <el-table-column label="发布时间">
          <template v-slot="scoped">
            {{ formatTime(scoped.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="danger" @click="doDel(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 1.3 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 2.全屏的dialog弹窗 -->
    <el-dialog :fullscreen="true" :visible.sync="addDialogVisible">
      <el-form label-position="right" label-width="80px" :model="addForm">
        <!-- (1)文章标题 -->
        <el-form-item label="文章标题">
          <el-input placeholder="请输入标题" v-model="addForm.title"></el-input>
        </el-form-item>
        <!-- (2)文章分类 -->
        <el-form-item label="文章分类">
          <el-select placeholder="请输入分类" v-model="addForm.cate_id">
            <el-option
              :value="item.id"
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- (3)文章内容 -->
        <el-form-item label="文章内容">
          <quill-editor v-model="addForm.content"></quill-editor>
        </el-form-item>
        <!-- (4)文章封面 -->
        <el-form-item label="文章封面">
          <img src="../../assets/images/avatar.jpg" alt="" ref="imgRef" />
          <input
            type="file"
            ref="inpRef"
            style="display: none"
            @change="doFileChange"
          />
          <br />
          <el-button type="primary" plain @click="$refs.inpRef.click()">
            + 选择封面</el-button
          >
        </el-form-item>
        <!-- (5)发布与存草稿按钮 -->
        <el-form-item>
          <el-button type="primary" @click="addArticle('已发布')"
            >发布</el-button
          >
          <el-button @click="addArticle('草稿')">存草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 3.文章信息的dialog弹窗 -->
    <el-dialog :visible.sync="infoDialogVisible" title="文章预览" width="80%">
      <h1 class="title">{{ articleInfo.title }}</h1>
      <div class="info">
        <span>作者：{{ articleInfo.nickname || articleInfo.username }}</span>
        <span>发布时间：{{ formatTime(articleInfo.pub_date) }}</span>
        <span>所属分类：{{ articleInfo.cate_name }}</span>
        <span>状态：{{ articleInfo.state }}</span>
      </div>
      <el-divider></el-divider>
      <img
        :src="'http://big-event-vue-api-t.itheima.net' + articleInfo.cover_img"
        alt=""
      />
      <div v-html="articleInfo.content"></div>
    </el-dialog>
  </div>
</template>

<script>
//导入富文本
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
//导入moment.js
import moment from "moment";
export default {
  name: "ArtList",
  //0.注册组件
  components: {
    quillEditor,
  },
  //1.数据
  data() {
    return {
      //1.1dialog全屏对话框的布尔值
      addDialogVisible: false,
      //1.2新增表单数据
      addForm: {
        title: "",
        cate_id: "",
        content: "",
        state: "",
        cover_img: "",
      },
      //1.3文章分类
      cateList: [],
      //1.4查询文章数据
      query: {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      },
      //1.5文章列表数据
      artList: [],
      //1.6文章总数量
      total: 0,
      //1.7文章信息对话框的布尔值
      infoDialogVisible: false,
      //1.8文章信息
      articleInfo: {},
    };
  },
  //2.方法
  methods: {
    //2.1图片预览
    doFileChange(e) {
      // (1)获取用户选择的图片
      const file = e.target.files[0];
      // (2)把file转化为url
      const url = URL.createObjectURL(file);
      //(3)设置img的url
      this.$refs.imgRef.src = url;
      //(4)将file对象绑定到data
      this.addForm.cover_img = file;
    },
    //2.2添加文章
    async addArticle(state) {
      // (1)将state绑定到data中
      this.addForm.state = state;
      // (2)将表单的数据放入formData中
      const fd = new FormData();
      //遍历this.addForm,然后fd.append() 添加到formData中
      for (const key in this.addForm) {
        fd.append(key, this.addForm[key]);
      }
      // (3)发送请求
      const { data: res } = await this.$axios.post("/my/article/add", fd);
      if (res.code === 0) {
        //发布成功:刷新文章分类列表+提示+dialog关闭
        this.getArtList();
        this.addDialogVisible = false;
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
    },
    //2.3获取文章列表
    async getArtList() {
      // (1)发送请求
      const { data: res } = await this.$axios.get("/my/article/list", {
        params: this.query,
      });
      // (2)绑定数据
      this.total = res.total;
      this.artList = res.data;
    },
    //2.4转换日期的格式
    formatTime(date) {
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    //2.5 每页条数变化
    handleSizeChange(size) {
      this.query.pagesize = size;
      //刷新
      this.getArtList();
    },
    //2.6 页码变化时
    handleCurrentChange(page) {
      this.query.pagenum = page;
      //刷新
      this.getArtList();
    },
    //2.7重置,让query恢复初始值
    doReset() {
      this.query = {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      };
      //刷新
      this.getArtList();
    },
    //2.8点击查看文章信息
    async showInfo(id) {
      //发送请求,将数据绑定到data中,显示文章详情
      const { data: res } = await this.$axios.get("/my/article/info", {
        params: { id },
      });
      if (res.code === 0) {
        this.articleInfo = res.data;
      }
      this.infoDialogVisible = true;
    },
    //2.9删除
    async doDel(id) {
      const confirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirm) {
        const { data: res } = await this.$axios.delete("/my/article/info", {
          params: { id },
        });
        if (res.code === 0) {
          this.$message.success(res.message);
          if (
            Math.ceil((this.total - 1) / this.query.pagesize) <
            this.query.pagenum
          ) {
            this.query.pagenum--;
          }
          //刷新文章列表
          this.getArtList();
        }
      }
    },
  },
  //3.生命周期钩子
  async created() {
    // (1)加载文章分类
    const { data: res } = await this.$axios.get("/my/cate/list");
    this.cateList = res.data;
    //(2)获取文章列表
    this.getArtList();
  },
};
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

/deep/ .ql-editor {
  min-height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
